package com.acme.bankapp.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.acme.domain.bank.Bank;
import com.acme.domain.bank.Client;
import com.acme.exceptions.BankException;
import com.acme.service.bank.BankConsoleService;
import com.acme.service.bank.BankService;

public class BankServer {
	Bank bank;
	ServerSocket providerSocket = null;
	Socket connection = null;
	ObjectOutputStream out;
	ObjectInputStream in;
	String message;
	Client clientConnected = null;
	
	public BankServer(Bank bank) {
		this.bank = bank;
	}
	
	public void connect(int port) throws IOException {
		providerSocket = new ServerSocket(port,10);
		System.out.println("Waiting for connection");
	}
	
	public void disconnect() throws IOException {
		in.close();
		out.close();
		providerSocket.close();		
	}
	
	public void clientConnect() throws IOException {
		connection = providerSocket.accept();
		System.out.println("Coonection received from: " + 
			connection.getInetAddress().getHostName());
		out = new ObjectOutputStream(connection.getOutputStream());
		out.flush();
		in = new ObjectInputStream(connection.getInputStream());
		sendMessage("connection succesfull!");
	}
	
	public void run() throws BankException, ClassNotFoundException, IOException {
		while(message != "bye") {
			this.process();			
		}
	}
	
	public void start(int port) throws IOException, ClassNotFoundException, BankException {
		this.connect(port);
		this.clientConnect();
		this.run();
	}
	
	void process() throws BankException, ClassNotFoundException, IOException {
		receiveMessage();
		if(message.matches("^add " + Bank.regLine.substring(1))) {
			this.bank.addClient(message.substring(4));
		} else if (message.equals("print balance")) {
			BankConsoleService.printBalance(this.bank);
		} else if (message.matches("^modify client ([-+]?[0-9]*) by ([-+]?[0-9]*\\.?[0-9]*)$")) {
			Pattern pattern = Pattern.compile("^modify client ([-+]?[0-9]*) by ([-+]?[0-9]*\\.?[0-9]*)$");
			Matcher matcher = pattern.matcher(message);
			while(matcher.find()) {
				BankService.modifyBank(this.bank, Integer.parseInt(matcher.group(1)), 0, Double.parseDouble(matcher.group(2)));				
			}
		} else if(message.equals("hi server")) {
			sendMessage("hi client");
		} else if(message.equals("bye")) {
			sendMessage("bye");
			disconnect();
		}
	}
	
	void receiveMessage() throws ClassNotFoundException, IOException {
		message = (String)in.readObject();
		System.out.println("client>" + message);
	}
	
	void sendMessage (final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("server>" + msg);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}
}
